package main

import (
	"fmt"
	"hello/raft"
	"net/rpc"
)

//默认的Leader节点
var LeaderNode = raft.Node{
	Id:   1,
	Addr: "127.0.0.1:8088",
}

var LeaderRpc *rpc.Client

func main() {
	var err error
	LeaderRpc, err = rpc.Dial("tcp", LeaderNode.Addr)
	//关闭连接
	defer LeaderRpc.Close()
	if err != nil {
		fmt.Println(LeaderNode.Addr + "连接失败！=>" + err.Error())
	} else {
		leaderNode := &raft.Node{}
		//获取Leader节点
		callErr := LeaderRpc.Call("Raft.GetLeaderNetAddrRpcCall", struct{}{}, leaderNode)
		if callErr != nil {
			fmt.Println("Raft.GetLeaderNetAddrRpcCall远程调用失败！" + callErr.Error())
			return
		}
		updateLeaderRpc(leaderNode)
		for {
			var data string
			fmt.Println("请输入数据")
			fmt.Scanln(&data)
			if data == "exit" {
				break
			}
			//向Leader节点提交数据
			callErr := LeaderRpc.Call("Raft.AddDataRpcCall", data, leaderNode)
			if callErr != nil {
				fmt.Println("AddDataRpcCall调用失败数据：" + data)
			}
			updateLeaderRpc(leaderNode)
		}
	}
}

/*
  更新Leader的RPC连接
*/
func updateLeaderRpc(leaderNode *raft.Node) {
	fmt.Printf("当前Leader的节点是%v\n", leaderNode)
	if leaderNode.Id != LeaderNode.Id {
		LeaderNode.Id = leaderNode.Id
		LeaderNode.Addr = leaderNode.Addr
		//先关闭原来的连接
		if LeaderRpc != nil {
			LeaderRpc.Close()
		}
		var err error
		LeaderRpc, err = rpc.Dial("tcp", LeaderNode.Addr)
		if err != nil {
			fmt.Println(LeaderNode.Addr + "连接失败！")
			LeaderRpc = nil
		}
	}
}
